// 创建 websocket.js文件
export default class WebsocketTask {
	constructor(url, time) {
		this.url = url
		this.data = null
		this.isOpenSocket = false
		// 心跳检测
		this.timeout = time
		this.heartbeat = null

		try {
			return this.connectSocketInit()
		} catch (e) {
			this.isOpenSocket = false
			this.reconnect();
		}
	}

	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {}
		})
		this.socketTask.onOpen((res) => {
			clearTimeout(this.heartbeat);
			this.isOpenSocket = true
			this.start();
			this.socketTask.onMessage((res) => {
				//接收消息
				console.log(JSON.parse(res.data))
				let refObj = JSON.parse(res.data)
				if (JSON.parse(res.data).code === 200) {
					uni.showToast({
						title: refObj.msg,
						duration: 3000
					})
					if (refObj.msg === "有人给你发送私信了") {
						console.log(uni.$store)
						uni.$store.dispatch("getAllChatList")
					}
				}
			})
		})

		this.socketTask.onClose(() => {
			console.log("重新连接")
			this.isOpenSocket = false;
			this.reconnect();
		})
	}

	//发送消息
	send(data) {
		this.socketTask.send({
			data,
		})
	}
	//开启心跳检测
	start() {
		this.heartbeat = setTimeout(() => {
			this.data = {
				msg: "心跳检测连接成功",
				mode: "heart_beat"
			}
			this.send(JSON.stringify(this.data));
		}, this.timeout)
	}
	// 重新连接
	reconnect() {
		clearInterval(this.heartbeat)
		if (!this.isOpenSocket) {
			setTimeout(() => {
				this.connectSocketInit();
			}, 3000)
		}
	}

}